<template>
  <el-card shadow="never" class="detail-box">
    <template v-if="!isEdit">
      <i class="edit el-icon-edit" v-if="showEdit" @click="isEdit = true"></i>
      <div class="detail-logo">
        <img :src="detail.icon" alt="">
      </div>
      <div class="detail-info">
        <div class="text1">
          <div style="max-width: 60%;white-space: nowrap;text-overflow: ellipsis;overflow: hidden; ">{{ detail.name }}</div>
          <el-button
              @click.stop=""
              type="info" size="mini"
              :icon="detail.properties === 'Private' ? 'el-icon-lock' : 'el-icon-unlock'">
            {{ detail.properties === 'Private' ? 'Private' : 'Public'}}
          </el-button></div>
        <div class="text2">Affiliated with {{ detail.affiliation }}</div>
        <div class="text3">{{ detail.description }}</div>
        <div class="text4" v-if="detail.meets && detail.meets.repeat === 'No Repeats'">Group meet start {{GlobalTimeformat(detail.meets.meetsTimeAtZone, '', $store.state.timeFormat)}} at {{ detail.meets.meetsTimeAtZone | hh($store.state.user.timezoneId) }}</div>
        <div class="text4" v-if="detail.meets && detail.meets.repeat === 'Daily'">Group meet start Every day at {{ detail.meets.meetsTimeAtZone | hh($store.state.user.timezoneId) }} {{ detail.meets.meetsTimeAtZone | tz($store.state.user.timezoneId) }}</div>
        <div class="text4" v-if="detail.meets && detail.meets.repeat === 'Weekly'">Group meet start Every {{detail.meets.meetsTimeAtZone | ee($store.state.user.timezoneId)}} at {{ detail.meets.meetsTimeAtZone | hh($store.state.user.timezoneId) }} {{ detail.meets.meetsTimeAtZone | tz($store.state.user.timezoneId) }}</div>
        <div class="text4" v-if="detail.meets && detail.meets.repeat === 'Monthly'">Group meet start Every {{detail.meets.meetsTimeAtZone | dd($store.state.user.timezoneId)}}th of the month at {{ detail.meets.meetsTimeAtZone | hh($store.state.user.timezoneId) }} {{ detail.meets.meetsTimeAtZone | tz($store.state.user.timezoneId) }}</div>
        <div class="text4" v-if="detail.meets && detail.meets.repeat === 'Quarterly'">Group meet start {{ detail.meets.meetsTimeAtZone | hh($store.state.user.timezoneId) }} on the {{detail.meets.meetsTimeAtZone | dd($store.state.user.timezoneId)}} of the {{detail.meets.meetsTimeAtZone | mm($store.state.user.timezoneId)}} month of each quarter {{ detail.meets.meetsTimeAtZone | tz($store.state.user.timezoneId) }}</div>
        <div class="text4" v-if="detail.meets && detail.meets.repeat === 'Annually'">Group meet start {{detail.meets.meetsTimeAtZone | mmm($store.state.user.timezoneId)}} {{ detail.meets.meetsTimeAtZone | dd($store.state.user.timezoneId) }}th of every year at {{ detail.meets.meetsTimeAtZone | hh($store.state.user.timezoneId) }} {{ detail.meets.meetsTimeAtZone | tz($store.state.user.timezoneId) }}</div>
      </div>
    </template>
    <el-row style="flex: 1" v-else>
      <el-col :span="4">
        <el-upload
            class="avatar-uploader"
            action=""
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleAvatarChange"
            :before-upload="beforeAvatarUpload">
          <img v-if="form.icon" :src="form.icon" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-col>
      <el-col :span="20">
        <el-form ref="form" :model="form" label-position="top" :rules="formRules">
          <el-form-item label="Name" prop="name" required>
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="Properties" prop="properties" required>
            <el-select v-model="form.properties" @change="isDisableCheckbox" placeholder="Please Select" style="width: 100%" popper-class="properties">
              <el-option v-for="item in propertiesOptions" :label="item.label" :value="item.value" :key="item.value">
                <div>
                  <span style="font-weight: bold">{{item.label}}</span>
                  <div class="properties-desc">{{item.desc}}</div>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-checkbox v-model="form.publicMembers" :disabled="form.properties === 'Private'">Public group members</el-checkbox>
          </el-form-item>
          <el-form-item label="Affiliation" prop="affiliation" required>
            <el-select v-model="form.affiliation" placeholder="Please Select" style="width: 100%">
              <el-option v-for="item in affiliationOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="Description" prop="description" required>
            <el-input type="textarea" :autosize="{ minRows: 3, maxRows: 6}" v-model="form.description"></el-input>
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="18">
              <el-form-item label="Group Meets" prop="meets.meetsDate">
                <el-date-picker type="datetime" placeholder="Please Select" v-model="form.meets.meetsDate" style="width: 100%;"></el-date-picker>
              </el-form-item>
            </el-col>
            <!--              <el-col :span="6">-->
            <!--                <el-time-picker-->
            <!--                    style="width: 100%;"-->
            <!--                    v-model="form.meets.meetsTime"-->
            <!--                    placeholder="Please Select">-->
            <!--                </el-time-picker>-->
            <!--              </el-col>-->
            <el-col :span="6">
              <el-form-item label="*" class="hide-item">
                {{getTz()}}
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item prop="meets.repeat">
            <el-select v-model="form.meets.repeat" placeholder="Please Select">
              <el-option v-for="item in groupMeetsOptions" :key="item" :label="item" :value="item"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item style="text-align: right">
            <el-button size="small" @click="isEdit = false;$emit('getGroupDetail')">Cancel</el-button>
            <el-button size="small" type="primary" @click="onSubmit">Save</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </el-card>
</template>

<script>
import moment from 'moment'
import { GlobalTimeformat } from '@/utils/common'
export default {
  name: 'detailInfo',
  props: ['detail', 'showEdit'],
  data () {
    const validateName = (rule, value, callback) => {
      value = value.trim()
      if (value === '') {
        return callback(new Error('Please Enter Name'))
      }
      if (value.length < 1 || value.length > 50) {
        return callback(new Error('1 to 50 characters in length'))
      }
      callback()
    }
    return {
      GlobalTimeformat,
      isEdit: false,
      form: {},
      formRules: {
        name: [
          { validator: validateName, trigger: 'blur' }
        ],
        'meets.meetsDate': [
          { required: true, message: 'Please enter', trigger: 'blur' }
        ]
      },
      propertiesOptions: [
        { label: 'Private', value: 'Private', desc: 'Only those invited by the captain can join the group.' },
        { label: 'Public', value: 'Public', desc: 'Anyone can join the group by applying to the group captain.' }
      ],
      groupMeetsOptions: ['No Repeats', 'Daily', 'Weekly', 'Monthly', 'Quarterly', 'Annually']
    }
  },
  filters: {
    YYYY (val, timezoneId) {
      return moment.tz(val, timezoneId).format('YYYY-MM-DD')
    },
    mm (val, timezoneId) {
      const m = moment.tz(val, timezoneId).format('M')
      const q = moment.tz(val, timezoneId).format('Q')
      const num = m - (q - 1) * 3
      const arr = ['first', 'second', 'Third']
      return arr[num - 1]
    },
    mmm (val, timezoneId) {
      return moment.tz(val, timezoneId).format('MMMM')
    },
    dd (val, timezoneId) {
      return moment.tz(val, timezoneId).format('DD')
    },
    hh (val, timezoneId) {
      return moment.tz(val, timezoneId).format('HH:mm')
    },
    ee (val, timezoneId) {
      return moment.tz(val, timezoneId).format('dddd')
    },
    tz (val, timezoneId) {
      return moment.tz(val, timezoneId).format('zz')
    }
  },
  computed: {
    edit () {
      return !!this.$route.query.edit
    },
    affiliationOptions () {
      const data = window.SITE_CONFIG['dictList'].find(e => e.dictType === 'get_started_about_peer_groups').dataList
      const arr = data.map(item => {
        return { label: item.dictLabel, value: item.dictLabel }
      })
      return arr.concat([
        { label: 'Encore', value: 'Encore' },
        { label: 'MSP Advisor', value: 'MSP Advisor' },
        { label: 'Bering McKinley', value: 'Bering McKinley' }
      ])
    }
  },
  watch: {
    detail (val) {
      this.form = val
    },
    edit: {
      handler: function (val) {
        this.isEdit = val
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    getTz () {
      return moment.tz.guess()
    },
    editInfo () {},
    async onSubmit () {
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          const { postUploadImg, updatePeerGroup } = this.$interface.system
          if (this.form.icon && !this.form.icon.includes('https://')) {
            const { data: img } = await postUploadImg({
              file: this.form.icon,
              path: 'apps',
              bucket: 'widget'
            })
            this.form.icon = img.data.src
          }
          const { data } = await updatePeerGroup(this.form)
          if (data.code === 0 && data.data) {
            this.$message.success('Success')
            this.$emit('getGroupDetail')
            this.isEdit = false
          } else {
            this.$message.error(data.msg)
          }
        } else {
          return false
        }
      })
    },
    handleAvatarChange (file, fileList) {
      const that = this
      const reader = new FileReader()
      reader.readAsDataURL(file.raw)
      reader.onload = function () {
        that.form.icon = this.result
      }
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('The uploaded avatar can only be in JPG format!')
      }
      if (!isLt2M) {
        this.$message.error('The size of the uploaded avatar image cannot exceed 2MB!')
      }
      return isJPG && isLt2M
    },
    isDisableCheckbox (val) {
      if (val === 'Private') {
        this.form.publicMembers = false
      }
    }
  }
}
</script>

<style>
.properties .el-select-dropdown__item{
  height: auto;
}
</style>
<style scoped lang="scss">
::v-deep .el-form-item{
  margin-bottom: 22px;
}
.detail-box {
  position: relative;
  background: #f3f3f3;
  ::v-deep .el-card__body {
    display: flex;
  }
  .edit {
    position: absolute;
    right: 20px;
    top: 18px;
    cursor: pointer;
    user-select: none;
  }
  .detail-logo {
    width: 70px;
    height: 70px;
    flex-shrink: 0;
    margin-right: 13px;
    img {
      width: 100%;
      height: 100%;
    }
  }
  .detail-info {
    width: 100%;
    .text1 {
      font-size: 20px;
      color: #1C0F30;
      line-height: 28px;
      display: flex;
      align-items: center;
      button {
        margin-left: 8px;
      }
    }
    .text2 {
      line-height: 16px;
      font-size: 12px;
      color: #00000072;
      margin: 4px 0;
    }
    .text3 {
      font-size: 14px;
      line-height: 20px;
      word-break: break-all;
    }
    .text4 {
      font-size: 14px;
      line-height: 20px;
      color: #0000009B;
      margin-top: 4px;
    }
  }
}
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.properties-desc{
  font-size: 12px;
  color: #0000009B;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  line-height: 78px;
  text-align: center;
}
.avatar {
  width: 78px;
  height: 78px;
  display: block;
}
::v-deep .el-upload::after {
  content: 'Upload';
  display: block;
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  line-height: 22px;
  background: #00000072;
  color: #FFFFFF;
  font-size: 12px;
}
::v-deep .hide-item .el-form-item__label {
  visibility: hidden;
}
</style>
